<?php
/**
 * projectname:gdu_cms2 
 * author:senman
 * time:2017/8/9 13:13
 */

namespace app\admin\controller;

use app\admin\builder\AdminConfigBuilder;
use app\admin\builder\AdminListBuilder;
use think\Db;
use think\exception\ErrorException;
use think\Request;


class User extends Auth
{
    protected $user_model;
    protected $group_model;
    protected $access_model;
    protected $user_id;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->auth();
        $this->group_model = model('Group');
        $this->user_model = model('User');
        $this->access_model = model('Access');
        $this->user_id = session('user_id');
    }


    /**
     * @describe 用户列表
     * @return mixed
     */
    public function userList()
    {
        $data = $this->user_model->select();
        if ($data) {
            foreach ($data as $k => $v) {
                if ($v['sex'] == 1) {
                    $data[$k]['sex'] = "男";
                } elseif ($v['sex'] == 2) {
                    $data[$k]['sex'] = "女";
                } else {
                    $data[$k]['sex'] = "未知";
                }
                if ($v['status'] == 0) {
                    $data[$k]['status'] = 1;
                } else {
                    $data[$k]['status'] = 0;
                }
            }
        }

        $builderlist = new AdminListBuilder();
        $builderlist->title('权限管理')->suggest('用户列表');
        $builderlist->keyText('id', 'ID');
        $builderlist->keyText('account', '账号');
        $builderlist->keyText('nickname', '昵称');
        $builderlist->keyImg('avatar', '头像');
        $builderlist->keyText('sex', '性别');
        $builderlist->keyText('email', '邮箱');
        $builderlist->keyText('tel', '手机');
        $builderlist->keyText('phone', '固话');
        $builderlist->keyText('create_time', '创建时间');
        $builderlist->keyText('update_time', '更新时间');

        if (checkAuth('admin/user/userAddHtml')) {
            $builderlist->buttonNew('新增', "", url('admin/user/userAddHtml'));
        }

        if (checkAuth('admin/user/updateHtml')) {
            $builderlist->keyDoActionLink(url('admin/user/updateHtml'), '编辑', 'btn-primary');
        }
        if (checkAuth('admin/user/changeState')) {
            $builderlist->keyDoActionPostTextChange(url('admin/user/changeState'), '启用', '禁用', 'status');
        }

        $builderlist->data($data);
        //写日志
        Log::writeLog("查看用户列表");
        return $builderlist->displayList();
    }

    /**
     * 新增用户界面
     * @return mixed
     */
    public function userAddHtml()
    {
        $builder = new AdminConfigBuilder();
        $builder->formsubmit('新增用户');
        $builder->keyText('account', '账号');
        $builder->keyText('nickname', '昵称');
        $builder->keyRadio('sex', '性别', '', ["1" => "男", "2" => "女", "3" => "未知"]);
        $builder->keyPassword('password', '密码');
        $builder->keyPassword('password2', '确认密码');
        $builder->keySingleImage('avatar', '头像');
        $builder->keyText('email', '邮箱');
        $builder->keyText('tel', '手机');
        $builder->keyText('phone', '电话');

        $groups = $this->group_model->where(['status' => 0])->field('id,name')->select();
        $group_arr = [];
        if ($groups) {
            foreach ($groups as $k => $v) {
                $group_arr[$v['id']] = $v['name'];
            }
        }
        $builder->keyCheckBox('group_id', '角色', '', $group_arr);
        $builder->keyText('remark', '备注说明');
        $builder->keyRadio('status', '状态', '', ["0" => "启用", "1" => "禁用"]);
        $builder->keyText('sort', '排序');
        $builder->buttonBack()->buttonSubmit(url('userAdd'));
        //写日志
        Log::writeLog("进入新增用户页面");
        return $builder->displayConfig();
    }

    /**
     * 新增用户界面
     * @return mixed
     */
    public function updateHtml()
    {
        $id = input('id');
        if (!$id > 0) {
            return json(['status' => 0, 'info' => "参数异常"]);
        }
        $data = $this->user_model->where(['id' => $id])->find();
        if (!$data) {
            return json(['status' => 0, 'info' => "操作异常"]);
        } else {
            $data['password'] = null;
        }


        $groups = $data->groups;
        $group_id_arr = [];
        if ($groups) {
            foreach ($groups as $k => $v) {
                if ($v['group_id'] > 0) {
                    $group_id_arr[] = $v['group_id'];
                }
            }
        }
        $group_id_str = @implode(',', $group_id_arr);
        $data['group_id'] = $group_id_str;
        $builder = new AdminConfigBuilder();
        $builder->formsubmit('新增用户');
        $builder->keyReadOnly('account', '账号');
        $builder->keyText('nickname', '昵称');
        $builder->keyRadio('sex', '性别', '', ["1" => "男", "2" => "女", "3" => "未知"]);
        $builder->keyPassword('password', '密码');
        $builder->keyPassword('password2', '确认密码');
        $builder->keySingleImage('avatar', '头像');
        $builder->keyText('email', '邮箱');
        $builder->keyText('tel', '手机');
        $builder->keyText('phone', '电话');

        $groups = $this->group_model->where(['status' => 0])->field('id,name')->select();
        $group_arr = [];
        if ($groups) {
            foreach ($groups as $k => $v) {
                $group_arr[$v['id']] = $v['name'];
            }
        }
        $builder->keyHidden('id');
        $builder->keyCheckBox('group_id', '角色', '', $group_arr);
        $builder->keyText('status', '状态');
        $builder->keyText('remark', '备注说明');
        $builder->keyRadio('status', '状态', '', ["0" => "启用", "1" => "禁用"]);
        $builder->keyText('sort', '排序');
        $builder->buttonBack()->buttonSubmit(url('userUpdate'));
        $builder->data($data);
        //写日志
        Log::writeLog("进入更改用户页面");
        return $builder->displayConfig();
    }

    /**
     * 修改用户
     * @return \think\response\Json
     */
    public function userUpdate()
    {
        $id = input('id');
        $validate = validate('User');
        if (!$validate->scene('update')->check(input())) {
            return json(['status' => 0, 'info' => lang($validate->getError())]);
        } else {
            Db::startTrans();
            try {

                $condition = [];
                $condition['id'] = ['neq', $id];
                $condition['email'] = input('email');
                $rs = $this->user_model->
                where($condition)->
                find();
                if ($rs) {
                    return json(['status' => 0, 'info' => "邮箱已经被占用"]);
                }

                $condition = [];
                $condition['id'] = ['neq', $id];
                $condition['tel'] = input('tel');
                $rs = $this->user_model->
                where($condition)->
                find();
                if ($rs) {
                    return json(['status' => 0, 'info' => "手机已经被占用"]);
                }

                $condition = [];
                $condition['id'] = $id;
                $rs = $this->user_model->
                where($condition)->
                find();
                if (!$rs) {
                    return json(['status' => 0, 'info' => "该用户异常"]);
                }

                $data = [];
                $data['nickname'] = trim(input('nickname'));
                $data['sex'] = trim(input('sex'));
                if (trim(input('password'))) {
                    if (input('password') == input('password2')) {
                        $data['password'] = md5(trim(input('password')));
                    } else {
                        return json(['status' => 0, 'info' => "密码不一致"]);
                    }
                }

                $data['email'] = trim(input('email'));
                $data['avatar'] = trim(input('avatar'));
                $data['tel'] = trim(input('tel'));
                $data['phone'] = trim(input('phone'));
                $data['remark'] = trim(input('remark'));
                $data['status'] = intval(input('status'));
                $data['update_time'] = time();

                $this->user_model->where(['id' => $id])->update($data);
                $this->access_model->where(['user_id' => $id])->delete();
                $group_id = trim(input('group_id'));
                //将该用户进行分组
                $group_data = [];
                $group_data['user_id'] = $id;

                if ($group_id) {
                    $group_arr = @explode(',', $group_id);
                    if ($group_arr) {
                        foreach ($group_arr as $gk => $gv) {
                            if ($gv > 0) {
                                $group_data['group_id'] = intval($gv);
                                $this->access_model->insert($group_data);
                            }

                        }
                    }

                }
                //写日志
                Log::writeLog("成功修改用户");
                DB::commit();
                return json(['status' => 1, 'info' => lang('OPERATE_SUCCESS'), 'url' => url('userList')]);
            } catch (\Exception $errorException) {
                DB::rollback();
                return json(['status' => 0, 'info' => lang('OPERATE_FAILE')]);
            }
        }

    }

    /**
     * 新增用户
     * @return \think\response\Json
     */
    public function userAdd()
    {
        $validate = validate('User');
        if (!$validate->scene('add')->check(input())) {
            return json(['status' => 0, 'info' => lang($validate->getError())]);
        } else {
            Db::startTrans();
            try {
                $rs = $this->user_model->
                whereOr(['account' => input('account')])->
                whereOr(['email' => input('email')])->
                whereOr(['tel' => input('tel')])->
                find();
                if ($rs) {
                    return json(['status' => 0, 'info' => "数据重复"]);
                }
                $data = [];
                $data['account'] = trim(input('account'));
                $data['nickname'] = trim(input('nickname'));
                $data['sex'] = trim(input('sex'));
                $data['password'] = md5(trim(input('password')));
                $data['email'] = trim(input('email'));
                $data['avatar'] = trim(input('avatar'));
                $data['tel'] = trim(input('tel'));
                $data['phone'] = trim(input('phone'));
                $data['remark'] = trim(input('remark'));
                $data['status'] = intval(input('status'));
                $data['create_time'] = time();
                $data['update_time'] = time();
                $query_id = $this->user_model->insertGetId($data);
                if ($query_id) {
                    $group_id = trim(input('group_id'));
                    //将该用户进行分组
                    $group_data = [];
                    $group_data['user_id'] = $query_id;
                    if ($group_id) {
                        $group_arr = @explode(',', $group_id);
                        if ($group_arr) {
                            foreach ($group_arr as $gk => $gv) {
                                if ($gv > 0) {
                                    $group_data['group_id'] = $gv;
                                    $this->access_model->insert($group_data);
                                }

                            }
                        }

                    }
                    //写日志
                    Log::writeLog("新增用户成功");
                    DB::commit();
                    return json(['status' => 1, 'info' => lang('OPERATE_SUCCESS'), 'url' => url('userList')]);
                } else {
                    DB::rollback();
                    return json(['status' => 0, 'info' => lang('OPERATE_FAILE')]);
                }

            } catch (ErrorException $errorException) {
                DB::rollback();
                return json(['status' => 0, 'info' => lang('OPERATE_FAILE')]);
            }


        }

    }


    /**
     * 修改状态
     */
    public function changeState()
    {
        $input = $this->request->post();
        $id = $input['id'];
        if ($input['publish'] == "publish") {
            $status = 0;//启用
        } else {
            $status = 1;//禁用
        }

        $condition = [];
        $admin_id_arr = @explode(",", config('auth.administrator'));
        if (in_array($id, $admin_id_arr)) {
            return json(['status' => 0, 'info' => "该用户是超级管理员，不可变更"]);
        }
        $condition['id'] = $id;
        $query = $this->user_model->where($condition)->update(['status' => $status]);
        if ($query) {
            //写日志
            Log::writeLog("修改用户状态");
            return json(['status' => 1, 'info' => lang('OPERATE_SUCCESS'), 'url' => url('admin/user/userList')]);
        } else {
            return json(['status' => 0, 'info' => lang('OPERATE_FAILE')]);
        }
    }


}